package com.hontech.kaltaapp.ui.parts

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.Button
import android.widget.FrameLayout
import com.hontech.kaltaapp.R
import com.hontech.kaltaapp.device.Conn
import com.hontech.kaltaapp.ui.dialog.runProg
import com.hontech.kaltaapp.ui.dialog.showErr
import com.hontech.kaltaapp.ui.view.LabelSpinner
import com.hontech.kaltaapp.utils.log
import com.hontech.kaltaapp.utils.onClick

class SerialPortParts(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.parts_serial_port, this)
        val sp = view.findViewById<LabelSpinner>(R.id.id_serial_sp_ports)
        val open = view.findViewById<Button>(R.id.id_serial_btn_open)
        val ping = view.findViewById<Button>(R.id.id_serial_btn_ping)
        open.onClick { onClickOpen(sp.selectText(), open) }
        ping.onClick { onClickPing() }

    }

    private suspend fun onClickPing() {
        runProg("Ping", "Ping") {
            Conn.ping()
        }
    }

    private suspend fun onClickOpen(name: String, btn: Button) {
        try {
            if (Conn.isOpen()) {
                Conn.close()
                btn.text = "打开"
                return
            }
            Conn.open(name)
            btn.text = "关闭"
        } catch (e: Exception) {
            e.printStackTrace()
            showErr("串口打开失败", e)
        }
    }

}